<?php
namespace Admin\Controller;

use Think\Controller;

class UserController extends Controller
{
    var $user;

    function __construct()
    {
        $this->user = M('User');
        parent::__construct();
    }

    public function register()
    {
        $this->display();
    }

    function do_register()
    {
        $User =D("User");//实例化User对象
         if(!$User->create()){
            $this->error($User->getError());
        } else {
             $data['username'] = trim(I("post.username"));
             $data['password'] = substr(md5(trim(I("post.password"))), 6, -6);
             $data['token'] = md5(uniqid() . time() . rand(1000000, 9999999));
            $User->add($data);
            $this->success('注册成功', U('login'));
        }

        
       /*
        *

        $data['username'] = trim(I("post.username"));
        $user = $this->user->where($data)->find();
        if ($user) {
            $this->error('用户名已经存在, 请更换用户名');
        }

        $data['password'] = substr(md5(trim(I("post.password"))), 6, -6);
        $data['token'] = md5(uniqid() . time() . rand(1000000, 9999999));
        $this->user->add($data);

        $this->success('注册成功', U('login'));
        */
    }
/*
 * 登录
 */
    function login()
    {
        $this->display();

    }
    function do_login()
    {

        $code = I("post.code");
        if (!$this->check_verify($code)) {
            $this->error('验证码错误!');
        }

        $data['username'] = trim(I("post.username"));
        $data['password'] = substr(md5(trim(I("post.password"))), 6, -6);

        $user = $this->user->where($data)->find();
        if (!$user) {
            $this->error('账号或密码错误!');
        }

        if (isset($_POST['rem'])) {
            setcookie('token', $user['token'], time() + 60 * 60 * 24 * 7, '/');
        } else {
            setcookie('token', $user['token'], null, '/');
        }

        $this->success("登录成功", U("Index/index"));
    }

    function logout()
    {
        $_SESSION = array();
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), "", time() - 3600, "/");
        }

        if (isset($_COOKIE['token'])) {
            setcookie('token', "", time() - 3600, "/");
        }
        $this->success('您已经安全退出', U('login'));
    }
    function verify()
    {

        $config =    array(
            'length'      =>    4,     // 验证码位数
            'useNoise'    =>    false, // 关闭验证码杂点
            'codeSet' => '0123456789',
        );
        $Verify =     new \Think\Verify($config);
        $Verify->entry();


    }
    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串
    function check_verify($code, $id = ''){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }


}